<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/15 0015
 * Time: 15:37
 */

namespace App\Socket\Packets;


use App\Socket\Models\Protocol;
use App\Socket\Services\SocketServer;
use App\User\Repositories\UserAuthRepository;
use Illuminate\Support\Facades\Cache;

class UserPacket
{
    /**
     * @var UserPacket
     */
    private static $instance;

    /**
     * @return UserPacket
     */
    public static function instance()
    {
        if (self::$instance == null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 用户登录
     * @param $data
     * @param int $fd
     * @return Protocol
     */
    public function login($data,int $fd)
    {
        $token = $data['token'] ?? '';
        $user = Cache::get(UserAuthRepository::PREFIX_TOKEN . $token);
        if (!empty($user)) {
            //绑定用户
            SocketServer::instance()->bind($fd,$user['id']);
            return Protocol::toObject([
                'code' => Protocol::CODE_LOGIN,
                'data' => $user
            ]);
        } else {
            return Protocol::toObject([
                'code' => Protocol::CODE_LOGIN,
                'success' => Protocol::ERROR,
                'message' => '授权失败'
            ]);
        }
    }

    /**
     * 用户注销
     * @param $data
     * @param int $fd
     */
    public function logout($data,int $fd)
    {
        SocketServer::instance()->close($fd);
    }
}